package config

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"github.com/sirupsen/logrus"
	"gopkg.in/yaml.v2"
)

var Instance *Config

type Config struct {
	AppDir      string       `yaml:"AppDir"`  // 程序位置
	Env         string       `yaml:"Env"`     // 环境：prod、dev
	BaseUrl     string       `yaml:"BaseUrl"` // base url
	Port        string       `yaml:"Port"`    // 端口
	LogLevel    string       `yaml:"LogLevel"`
	LogFile     string       `yaml:"LogFile"`     // 日志文件
	LoginModule string       `yaml:"LoginModule"` // 登录验证模块
	ShowSql     bool         `yaml:"ShowSql"`     // 是否显示日志
	StaticPath  string       `yaml:"StaticPath"`  // 静态文件目录
	DataSources []DataSource `yaml:"DataSources"`
	Cache       []Region     `yaml:"Region"`
	Redis       []RedisConf  `yaml:"Redis"`
	MySqlUrl    string       `yaml:"MySqlUrl"` // 数据库连接地址
}
type DataSource struct {
	Name            string `yaml:"Name"`
	DriverName      string `yaml:"DriverName"`
	DataSourceName  string `yaml:"DataSourceName"`
	MaxOpenConns    int    `yaml:"MaxOpenConns"`
	MaxIdleConns    int    `yaml:"MaxIdleConns"`
	ConnMaxIdleTime int    `yaml:"ConnMaxIdleTime"`
	ConnMaxLifeTime int    `yaml:"ConnMaxLifeTime"`
}

type Region struct {
	Name   string `yaml:"Name"`
	Size   int    `yaml:"Size"`
	Expire int    `yaml:"Expire"`
}

type RedisConf struct {
	Name             string `yaml:"Namespace"`
	Storage          string `yaml:"Storage"`
	Channel          string `yaml:"Channel"`
	Scheme           string `yaml:"Scheme"`
	Hosts            string `yaml:"Hosts"`
	Password         string `yaml:"Password"`
	Database         int    `yaml:"Database"`
	SentinelMasterId string `yaml:"SentinelMasterId"`
	MaxTotal         int    `yaml:"MaxTotal"`
	MaxIdle          int    `yaml:"MaxIdle"`
	Timeout          int    `yaml:"Timeout"`
}

func Init(filename string) *Config {
	Instance = &Config{}
	configFile := filename
	logrus.Info("cur root is:", getCurrentDir())
	if strings.Index(filename, ":") < 0 {
		configFile = getCurrentDir() + filename
	}
	if yamlFile, err := ioutil.ReadFile(configFile); err != nil {
		logrus.Error(err)
	} else if err = yaml.Unmarshal(yamlFile, Instance); err != nil {
		logrus.Error(err)
	}
	Instance.AppDir = getCurrentDir()
	return Instance
}

/*
获取程序运行路径
*/
func getCurrentDir() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		logrus.Error(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}
